import { ref, reactive, onMounted, nextTick } from 'vue';
import { emitter } from "@/utils/mitt";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from 'vue-router';
import {
  ProRiskGetOption,
  ProRiskInsert,
  ProRiskGetProRisk
} from "@/api/stu/InsuranceData";
import { SpliceDate } from "@/utils/public/method"
import { type PaginationProps } from "@pureadmin/table";
import qs from 'qs';

export function useNewRiskControlModel() {
  const route = useRoute()
  const loading = ref(true);
  const Refform = ref();
  const spanMap = ref({});
  const DialogVisible = ref(false);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 30,
    currentPage: 1,
    pageSizes: [5, 10, 30],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "模型名称",
      prop: "name",
    },
    {
      label: "创建时间",
      prop: "createTime",
      cellRenderer: ({ row }) => (
        <span>{SpliceDate(row.createTime)}</span>
      )
    }
  ];
  const underrules = ref([]);//核保结果
  const Risklevel = ref([]);//风险等级
  const RulesWriting = ref([]); // 除外承保
  const SeleteTypeList = ref();
  const SeleteTypeList2 = ref([]);
  const changeSeletesList = ref([]);
  const marktabdata = ref([
    { id: "1" },
    { id: "2" },
    { id: "3" },
    { id: "4" },
  ])
  const form = reactive({
    name: "",
    createTime: "",
    dataType: [],
    selectParms: [],
    smark1: "",
    smark2: "",
    smark3: "",
    smark4: "",
    smark5: "",
    smark6: "",
    smark7: "",
    smark8: "",
    smark9: "",
    smark10: "",
    smark11: "",
    smark12: "",
    smark13: "",
    smark14: "",
    smark15: "",
    smark16: "",
    smark17: "",
    smark18: "",
    smark19: "",
    smark20: "",
    smark21: "",
    smark22: "",
    smark23: "",
    smark24: "",
    smark25: "",
    smark26: "",
    smark27: "",
    smark28: "",
    smark29: "",
    smark30: "",
    smark31: "",
    smark32: "",
    smark33: "",
    smark34: "",
    smark35: "",
    smark36: "",
    smark37: "",
    smark38: "",
    smark39: "",
    smark40: "",
    smark41: "",
    smark42: "",
    smark43: "",
    smark44: "",
    smark45: "",
    smark46: "",
    smark47: "",
    smark48: "",
    smark49: "",
    smark50: "",
    smark51: "",
    smark52: "",
    smark53: "",
    smark54: "",
    smark55: "",
    smark56: "",
    smark57: "",
    smark58: "",
    smark59: "",
    smark60: "",
    smark61: "",
    smark62: "",
    smark63: "",
    smark64: "",
    smark65: "",
    smark66: "",
    smark67: "",
    smark68: "",
    smark69: "",
    smark70: "",
    smark71: "",
    smark72: "",
    smark73: "",
    smark74: "",
    smark75: "",
    smark76: "",
    smark77: "",
    smark78: "",
    smark79: "",
    smark80: "",
    smark81: "",
    smark82: "",
    smark83: "",
    smark84: "",
    // 权重
    weight1: "",
    weight2: "",
    weight3: "",
    weight4: "",
    weight5: "",
    weight6: "",
    weight7: "",
    weight8: "",
    weight9: "",
    weight10: "",
    weight11: "",
    weight12: "",
    weight13: "",
    weight14: "",
    weight15: "",
    weight16: "",
    weight17: "",
    weight18: "",
    weight19: "",
    weight20: "",
    weight21: "",
    weight22: "",
    weight23: "",
    weight24: "",
    weight25: "",
    weight26: "",
    weight27: "",
    weight28: "",
    weight29: "",
    weight30: "",
    weight31: "",
    weight32: "",
    weight33: "",
    weight34: "",
    // 最终得分
    kmark11: "",
    kmark12: "",
    kmark21: "",
    kmark22: "",
    kmark31: "",
    kmark32: "",
    kmark41: "",
    kmark42: "",
    // 风险等级
    isklevel1: "",
    isklevel2: "",
    isklevel3: "",
    isklevel4: "",
    // 结果
    rules1: "",
    rules2: "",
    rules3: "",
    rules4: "",
    //
    writing: []//选中除外承保时
  });


  function handleSizeChange(val) {
    GetModelDataList()
  }

  function handleCurrentChange(val) {
    GetModelDataList()
  }

  const btnloading = ref<boolean>(false);
  // 将选中的多个数据子级放入新的数组中
  function hanTypeList(row) {
    let Arry = [];
    form.selectParms = "";
    changeSeletesList.value = [];
    SeleteTypeList.value.forEach(r => {
      row.forEach(l => {
        if (r.dictId === l) {
          r.params.forEach((s) => {
            const obj = {
              label: r.dictName,
              dictId: s.dictId,
              type: s.type,
              pid: s.pId,
              dictName: s.dictName,
              paramValues: s.paramValues
            }
            Arry.push(obj)
          })
        }
      })
    });
    SeleteTypeList2.value = Arry
  }

  // 选中二级传给子组件
  function changeSeletes(row) {
    let arry = [];
    SeleteTypeList2.value.forEach(r => {
      row.forEach(l => {
        if (r.dictId === l) {
          arry.push(r)
        }
      })
    })
    changeSeletesList.value = arry;
  }

  // 打开新建窗口
  function handDialogVisible() {
    DialogVisible.value = true;
    // 重新渲染数据
    GetModelList()
  }

  // 获取子组件数据并提交
  function StubimMark(row: FormInstance) {
    if (!row) return;
    (row as any).validate(async valid => {
      if (!valid) return
      // 权重分 和 详情分
      let smarkobj = {}
      let weightobj = {}
      let kmarkobj = {}//最终得分
      let isklevelobj = {}; //风险等级
      let rulesobj = {}; //核保结果
      for (let key in form) {
        if (key.includes('smark')) {
          smarkobj[key.substring(5)] = form[key]
        }
        if (key.includes('weight')) {
          weightobj[key.substring(6)] = form[key]
        }
        if (key.includes('kmark')) {
          kmarkobj[key.substring(5)] = form[key]
        }
        if (key.includes('isklevel')) {
          isklevelobj[key.substring(8)] = form[key]
        }
        if (key.includes('rules')) {
          rulesobj[key.substring(5)] = form[key]
        }
      }
      const result = [];
      for (const key in kmarkobj) {
        const firstValue = key.charAt(0);
        if (isklevelobj.hasOwnProperty(firstValue) && rulesobj.hasOwnProperty(firstValue)) {
          if (!result[firstValue]) {
            result[firstValue] = {};
          }
          result[firstValue]['score' + key.substring(1)] = kmarkobj[key];
          result[firstValue]["riskLv"] = isklevelobj[firstValue]['dictName'];
          result[firstValue]["riskLvId"] = isklevelobj[firstValue]['dictId'];
          result[firstValue]["riskResult"] = rulesobj[firstValue];
          // console.log("s003", result[firstValue]["riskLv"])
        }
      }
      for (let l in result) {
        if (result[l].riskResult.underwriting) {
          result[l]['ExcUnder'] = form.writing
        }
      }
      const newArr = result.filter(item => item !== null);

      // 新得分数组对象
      const obj1 = changeSeletesList.value.map(ea => {
        let weight = null;
        for (let r in weightobj) {
          if (r == ea.pid) {
            weight = weightobj[r];
            break;
          }
        }
        // 输入的分值
        const child = ea.paramValues.map(eb => {
          let score = null;
          for (let t in smarkobj) {
            if (t == eb.id) {
              score = smarkobj[t];
              break;
            }
          }
          return {
            param: eb.paramValue,
            score: score
          };
        });

        return {
          ...ea,
          weight: weight,
          child: child
        };
      });
      // TOD 最终得分
      const nums = obj1.reduce((total, obj) => total + Number(obj.weight), 0);
      if (nums !== 100) {
        ElMessage.warning('权重之和必需等于100%');
        return
      }
      // success
      const data = {
        taskId: route.query.taskId,
        planId: route.query.planId,
        rName: form.name,
        createTime: form.createTime,
        type: { param: obj1 },
        score: newArr,
        dataType: form.dataType
      }
      btnloading.value = true;
      const res = await ProRiskInsert(data);
      if (res.success) {
        ElMessage.success(res.msg);
        GetModelDataList()
        RemoveMark(row)
        btnloading.value = false;
      } else {
        ElMessage.error(res.msg);
        setTimeout(() => { btnloading.value = false; }, 1500)
      }
    })
  }

  // 选择核保结果-除外承保
  function ChangeRules(row) {
    if (row.stae) return;
    if (row.underwriting) {
      nextTick(() => {
        RulesWriting.value = row.underwriting;
      })
    }
    underrules.value.forEach(el => {
      if (row.dictId == el.dictId) {
        return el.state = true;
      }
    })
  }

  function RemoveMark(row: FormInstance) {
    DialogVisible.value = false;
    changeSeletesList.value = [];
    form.writing = [];
    // form.rules.state = false;
    for (let key in form) {
      if (key.includes('kmark')) form[key] = "";
    }
    row.resetFields();
  }
  // 整理table格式
  const objectSpanMethod = ({ column, rowIndex }) => {
    if (spanMap[column.property]) {
      const _row = spanMap[column.property].spanArr[rowIndex];
      const _col = _row > 0 ? 1 : 0;
      return {
        rowspan: _row,
        colspan: _col
      }
    }
  }

  // 获取数据列表
  async function GetModelList() {
    const res = await ProRiskGetOption();
    if (res.success) {
      SeleteTypeList.value = res.data.type;
      Risklevel.value = res.data.lv;
      underrules.value = res.data.results;
    } else {
      ElMessage.error(res.msg)
    }
  }

  // 获取模型列表
  async function GetModelDataList() {
    const data = {
      "pageIndex": pagination.currentPage,
      "pageCount": pagination.pageSize,
      "taskId": route.query.taskId,
      "planId": route.query.planId,
    };
    const res = await ProRiskGetProRisk(data);
    if (res.success) {
      dataList.value = res.data?.items;
      pagination.total = res.data?.totalCount;
      loading.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => {
        loading.value = false
      }, 1500)
    }
  }

  function SetKmark1(event, row) {
    if (event == 'none') return
    form['kmark' + (event + 1) + '1'] = row
  }

  onMounted(() => {
    GetModelList()
    GetModelDataList()
  })

  return {
    form,
    Refform,
    loading,
    columns,
    dataList,
    Risklevel,
    underrules,
    btnloading,
    marktabdata,
    RulesWriting,
    SeleteTypeList,
    SeleteTypeList2,
    pagination,
    DialogVisible,
    changeSeletesList,
    SetKmark1,
    RemoveMark,
    StubimMark,
    ChangeRules,
    hanTypeList,
    changeSeletes,
    handDialogVisible,
    handleSizeChange,
    objectSpanMethod,
    handleCurrentChange
  }
}
